<template>
  <JPopup ref="popup" @onClose="reset" @onOpen="isFlag">
    <view class="register-main bgF" v-if="flag">
      <LoginInput
        title="手机号"
        v-model:value="registerInfo.phone"
        place="请输入注册手机号"
        type="number"
        :rules="{ name: 'phone', rule: 'REG_Phone' }"
        pd="50rpx 50rpx 35rpx 50rpx"
      >
        <view class="sms-tips" v-if="registerInfo.phone.length == 11" @tap="createInterval">
          <text v-if="smsNumber != 60">{{ smsNumber }}s</text>
          {{ smsNumber !== 60 ? '后可重新发送' : '发送验证码' }}
        </view>
      </LoginInput>
      <LoginInput
        title="验证码"
        v-model:value="registerInfo.code"
        place="请输入短信验证码"
        type="number"
        :rules="{ name: 'code', rule: 'REG_NotNUll' }"
        pd="0 50rpx 35rpx 50rpx"
      ></LoginInput>
      <LoginInput
        title="代理商名称"
        v-model:value="registerInfo.agentName"
        place="请输入代理商名称"
        :rules="{ name: 'agentName', rule: 'REG_NotNUll' }"
        pd="0 50rpx 35rpx 50rpx"
      ></LoginInput>

      <LoginInput
        title="密码"
        v-model:value="registerInfo.password"
        place="请输入密码"
        :rules="{ name: 'password', rule: 'REG_NotNUll' }"
        :password="!isPassword"
        pd="0 50rpx 35rpx 50rpx"
      >
        <view class="right-eyes" @tap="isPassword = !isPassword">
          <image :src="eyeImg[isPassword ? 1 : 0]" mode="scaleToFill" />
        </view>
      </LoginInput>
      <LoginInput
        title="确认密码"
        v-model:value="registerInfo.confirmPwd"
        :rules="{ name: 'confirmPwd', rule: 'REG_NotNUll' }"
        place="请再次输入密码"
        :password="!isOpenEyes"
        pd="0 50rpx 35rpx 50rpx"
      >
        <view class="right-eyes" @tap="isOpenEyes = !isOpenEyes">
          <image :src="eyeImg[isOpenEyes ? 1 : 0]" mode="scaleToFill" />
        </view>
      </LoginInput>
      <LoginInput title="邀请码" v-model:value="registerInfo.inviteCode" place="请输入邀请码（选填）" pd="0 50rpx 70rpx 50rpx"></LoginInput>
      <view class="agreement-wrapper">
        <button class="agree-item" id="agree-btn" open-type="agreePrivacyAuthorization"
            @agreeprivacyauthorization="handAgree">
        <view class="agreement-garden" :class="[selected ? 'selected' : '']" @tap="selected = !selected"></view>
        </button>
        同意
        <view @tap="toPage('/pages/login/serviceAgreement')"> 《用户服务协议》 </view>
        与
        <view @tap="toPrivacy"> 《隐私政策》 </view>
      </view>
      <view class="register-button">
        <view @tap="close">取消</view>
        <view class="confirm" @tap="confirm">确认注册</view>
      </view>
    </view>
  </JPopup>
  <JAgree service="/pages/login/serviceAgreement" privacy="/pages/login/privacyPolicy" ref="refAgr" @agree="selected = true"/>
</template>
<script setup>
import { ref, reactive, onMounted } from 'vue'
import { $sendMessage, $register, $getPasswordRules } from '@/http/apiManager.js'
import { Base64 } from 'js-base64'
import { validateArray } from '@/hooks/rules'
import LoginInput from '@/components/newComponents/LoginInput/LoginInput'
import JPopup from '@/components/newComponents/JPopup/JPopup'
onMounted(() => {
  getRules()
})
const vdata = reactive({})
const popup = ref(null)
const refAgr = ref(null)
const flag = ref(false)
const rules = ref({}) //密码规则
const registerInfo = ref({
  phone: '',
  inviteCode: '',
})
const eyeImg = reactive(['/static/loginImg/login-eye-close.svg', '/static/loginImg/login-eye-open.svg'])
const selected = ref(false)
const isOpenEyes = ref(false)
const isPassword = ref(false)
const emits = defineEmits(['registerClose'])
const smsNumber = ref(60)
let interval = null
// 创建定时器
let createInterval = () => {
  if (interval) return
  sendMsg()
  interval = setInterval(() => {
    openInterval()
  }, 1000)
}
const getRules = () => {
  $getPasswordRules().then((res) => {
    rules.value.rule = new RegExp(res.bizData.regexpRules)
    rules.value.ruleText = res.bizData.errTips
  })
}
// smsNumber -1 倒计时
const openInterval = () => {
  smsNumber.value--
  if (smsNumber.value <= 0) {
    smsNumber.value = 60
    clearInterval(interval)
    interval = null
  }
}
// 发送短信验证码"
const sendMsg = () => {
  if (interval) return
  $sendMessage({
    phone: registerInfo.value.phone,
    smsType: 'register',
  })
    .then((res) => {
      const { bizData } = res

      uni.showToast({
        title: '发送成功',
        icon: 'success',
        mask: true,
      })
    })
    .catch((err) => {
      clearInterval(interval)
      interval = null
    })
}
const isFlag = () => {
  flag.value = true
}
const open = () => {
  popup.value.open()
}
const close = () => {
  reset()
  popup.value.close()
}
const reset = () => {
  flag.value = false
  registerInfo.value = { phone: '' }
}
// 确认注册
const confirm = () => {
 
  if (validateArray(registerInfo.value)) {
    if (registerInfo.value.password !== registerInfo.value.confirmPwd)
      return uni.showToast({
        title: '两次密码输入不一致',
        icon: 'none',
        mask: true,
      })
    if (!rules.value.rule.test(registerInfo.value.confirmPwd))
      return uni.showToast({
        title: rules.value.ruleText,
        icon: 'none',
      })
      if (!selected.value)
    return refAgr.value.open()
    uni.showLoading({
      title: '正在注册中',
      mask: true,
    })
    $register({
      agentName: registerInfo.value.agentName,
      phone: Base64.encode(registerInfo.value.phone),
      code: Base64.encode(registerInfo.value.code),
      confirmPwd: Base64.encode(registerInfo.value.confirmPwd),
      inviteCode: registerInfo.value.inviteCode,
    }).then((res) => {
      uni.hideLoading()
      uni.showToast({
        title: '注册成功请登录',
        icon: 'none',
        mask: true,
      })
      close()
    })
  }
}
// 隐私政策页面
const toPrivacy = () => {
    // #ifdef APP-PLUS  
    uni.navigateTo({
        url: '/pages/login/privacyPolicy',
    })
    // #endif

    // #ifdef MP-WEIXIN
    wx.openPrivacyContract(
        {
            fail: () => {
                uni.showToast({
                    title: '打开失败请稍后重试', // 打开失败
                    icon: 'none'
                })
            },
        }
    )
    // #endif
}

// #ifdef MP-WEIXIN
const getPrivacy = () => {
    wx.getPrivacySetting({
        success: (r) => {
            Object.assign(vdata, r)
            if (vdata.needAuthorization) {
                wx.onNeedPrivacyAuthorization(res => {
                    vdata.resolve = res
                })
            }
        }
    })
}
getPrivacy()
// #endif
const handAgree = () => {
    // #ifdef MP-WEIXIN
    if (vdata.needAuthorization) {
        vdata.resolve({ buttonId: 'agree-btn', event: 'agree' })
    }
    // #endif
}
const toPage = (url) => {
  uni.navigateTo({ url })
}
defineExpose({ open })
</script>

<style lang="scss" scoped>
.register-main {
  width: 100%;
  height: 70vh;
  overflow-y: scroll;
  border-radius: 32rpx 32rpx 0px 0px;
  .register-button {
    display: flex;
    justify-content: space-between;
    padding: 0 30rpx 70rpx 30rpx;
    view {
      flex: 1;
      padding: 32rpx;
      margin: 0 20rpx;
      border-radius: 20rpx;
      background-color: #f2f2f2;
      text-align: center;
    }
    .confirm {
      background-color: $primaryColor;
      color: #fff;
    }
  }
}
.agreement-wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  font-size: 24rpx;
  white-space: nowrap;
  transform: translateY(-40rpx);
  color: #8c8c8c;
  view {
    margin: 0 10rpx;
    color: $primaryColor;
  }
  .agreement-garden {
    position: relative;
    width: 30rpx;
    height: 30rpx;
    border-radius: 50%;
    border: 2rpx solid $primaryColor;
    &::after {
      content: '';
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      display: block;
      width: 80%;
      height: 80%;
      border-radius: 50%;
    }
  }
}
.selected::after {
  background-color: $primaryColor;
}
.sms-tips {
  font-size: 28rpx;
  color: $primaryColor;
  margin-right: 30rpx;
}
.right-eyes {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 110rpx;
  height: 110rpx;
  background-color: transparent;
}
image {
  width: 36rpx;
  height: 36rpx;
}
.agree-item {
    padding: 0;
    margin: 0;
    line-height: 0;
    border-radius: 0;
    background-color: transparent;
    &::after{
        display: none;
    }
}
</style>
